package com.npsngs.hawkeye;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.Comparator;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

public class FileSelectActivity extends Activity {
	private TextView textView = null;
	private GridView gridView = null;
	private MyFileAdapter adapter = null;
	private String lastPath = null;
	@SuppressLint("WorldWriteableFiles")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file);
		textView = (TextView) findViewById(R.id.curPath_text);
		gridView = (GridView) findViewById(R.id.files_grid);
		SharedPreferences sharedPref = getSharedPreferences("history", Context.MODE_WORLD_WRITEABLE);
		lastPath = sharedPref.getString("lastPath", "");
		if(lastPath.contentEquals("")){
			lastPath = getSDPath();
			if(null == lastPath){
				textView.setText(R.string.no_sdcard);
				return ;
			}
		}
		textView.setText(lastPath);
		
		adapter = new MyFileAdapter();
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				File selectFile = (File) adapter.getItem(position);
				Intent data = new Intent();
				if(selectFile.isFile()){
					SharedPreferences sharedPref = getSharedPreferences("history", Context.MODE_WORLD_WRITEABLE);
					Editor editor = sharedPref.edit(); 
					editor.putString("lastFile", selectFile.getAbsolutePath());
					editor.commit();
					
					data.putExtra("path", selectFile.getAbsolutePath());
					setResult(RESULT_OK, data);	
					finish();
				}else if(selectFile.isDirectory()){
					lastPath = selectFile.getAbsolutePath();
					adapter.cd(lastPath);
					adapter.notifyDataSetChanged();
				}
			}
		});
	}

	class MyFileAdapter extends BaseAdapter{
		private File[] fileList = null;
		private FileFilter fileFilter = null;
		private String pattern = null;
		public MyFileAdapter() {
			// TODO Auto-generated constructor stub
			cd(lastPath);
		}
		
		private void cd(String path){
			lastPath = path;
			textView.setText(path);
			File curDir = new File(path);
			if(curDir.exists() && curDir.isDirectory()){
				pattern = ".+\\.(png|jpg|jpeg|bmp)";
				fileFilter = new FileFilter() {
					@Override
					public boolean accept(File pathname) {
						// TODO Auto-generated method stub
						if(!pathname.isHidden() && pathname.isDirectory()){
							return true;
						}else if(!pathname.isHidden() && pathname.isFile()){
							return pathname.getName().matches(pattern);
						}
						return false;
					}
				};
				fileList = curDir.listFiles(fileFilter);
				sort(fileList);
			}
		}
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if(null != fileList){
				return fileList.length;
			}
			return 0;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			if(null != fileList){
				return fileList[position];
			}
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = convertView;
			FileViewHolder holder = null;
			if(null == view){
				view = View.inflate(getApplicationContext(), R.layout.item_file, null);
				holder = new FileViewHolder();
				holder.imageView = (ImageView) view.findViewById(R.id.image_filetype);
				holder.textView = (TextView) view.findViewById(R.id.text_filename);
				view.setTag(holder);
			}else{
				holder = (FileViewHolder) view.getTag();
			}
			File item = fileList[position];
			holder.textView.setText(item.getName());
			if(item.isDirectory()){
				holder.imageView.setImageResource(R.drawable.diricon);
			}else{
				holder.imageView.setImageBitmap(getNail(80,item.getAbsolutePath()));
			}
			return view;
		}
		
		private void sort(File[] lists){
			Arrays.sort(fileList);
			Arrays.sort(fileList, new Comparator<File>() {
				@Override
				public int compare(File file1, File file2) {
					// TODO Auto-generated method stub
					if(file1.isDirectory() && !file2.isDirectory()){
						return -1;
					}else if(!file1.isDirectory() && file2.isDirectory()){
						return 1;
					}else{
						return 0;
					}
				}
			});
		}
	}
	
	
	class FileViewHolder{
		TextView textView;
		ImageView imageView;
	}
	private String getSDPath() {
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); 
		if (sdCardExist) {
			return Environment.getExternalStorageDirectory().toString();
		} else {
			return null;
		}
	}
	
	private int sampleScale(int size, int w, int h) {
		int oldSize = w > h ? w : h;
		int power = 0;
		if (oldSize <= size) {
			power = 0;
		} else {
			while (true) {
				power++;
				if ((2 ^ power) * size <= oldSize
						&& (2 ^ (power + 1)) * size > oldSize) {
					break;
				}
			}
		}
		return 2 ^ power;
	}
	
	private Bitmap getNail(int size,String pathName){
		Options opts = new Options();
		BitmapFactory.decodeFile(pathName, opts);
		opts.inSampleSize = sampleScale(size, opts.outWidth, opts.outHeight);
		return BitmapFactory.decodeFile(pathName, opts);
	}

	@SuppressLint("WorldWriteableFiles")
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		SharedPreferences sharedPref = getSharedPreferences("history", Context.MODE_WORLD_WRITEABLE);
		Editor editor = sharedPref.edit(); 
		editor.putString("lastPath", lastPath);
		editor.commit();
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if(null != lastPath){
			String sdPath = getSDPath();
			if(lastPath.contentEquals(sdPath)){
				super.onBackPressed();
			}
			File file = new File(lastPath);
			adapter.cd(file.getParent());
			adapter.notifyDataSetChanged();
		}else{
			super.onBackPressed();
		}
	}
	
}
